package com.drs.challenge.controller;

import com.drs.challenge.bean.Audio;
import com.drs.challenge.service.AudioService;
import com.drs.challenge.tool.QRCodeGenerator;
import com.drs.challenge.tool.R;
import com.google.zxing.WriterException;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author Jasmine-drs
 * @date 2023/7/6 9:14
 */

@Slf4j
@RestController
@RequestMapping("/audios")
public class AudioController {

	private final AudioService audioService;

	public AudioController(AudioService audioService) {
		this.audioService = audioService;
	}

	/**
	 * 保存音频
	 * @param audio 音频
	 * @param uuid  uuid
	 * @return  success
	 */
	@PostMapping
	@ApiModelProperty("保存音频")
	public R<String> save(@RequestParam("audio") MultipartFile audio, @RequestParam("uuid") String uuid) {
		log.debug("audioController.save");
		try {
			log.debug("audio = " + Arrays.toString(audio.getBytes()));
			byte[] bytes = audio.getBytes();
			log.debug("bytes = " + Arrays.toString(bytes));
			audioService.saveAudio(bytes, uuid);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.success("success");
	}

	@GetMapping("/{uuid}")
	@ApiModelProperty("获取音频")
	public R<Audio> getAudio(@PathVariable("uuid") String uuid) {
		log.debug("audioController.getAudio");
		return R.success(audioService.getAudio(uuid));
	}

	@GetMapping("/qr")
	public R<String> getQR() {
		log.debug("audioController.getQR");
		String id = UUID.randomUUID().toString().replaceAll("-", "");
		log.debug("id = " + id);
//		String url = "http://1.12.249.127:8087/templates/index.html?id=" + id;
		String url = "https://drs.mynatapp.cc/templates/index.html?id=" + id;
//		String url = "https://drs.mynatapp.cc/templates/vidio.html?id=" + id;
		try {
			byte[] qrCode = QRCodeGenerator.generateQRCode(url, 300, 300);
			audioService.saveAudioInQRCode(qrCode, id);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return R.success("success");
	}

}
